﻿/**
 * ...
 * @author Артём Григорьев
 */

package tab;

import api.DAO;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import gui.hug.HUGTabbedPanel;

import gui.hug.HUGLinkButton;
import gui.hug.HUGSprite;
import gui.hug.Tab;

import loader.Loader;

import client.Category;

class CategoriesTab extends Tab
{

	private static inline var TITLE = "Облако тэгов";
	
	private var loader : Loader;
	private var viewerId : UInt;
		
	public function new(panel : HUGTabbedPanel = null, uid : UInt) 
	{
		var sprite : HUGSprite = new HUGSprite();
		Loader.createInstance();
		loader = Loader.getInstance();
		viewerId = uid;
				
		super(sprite, TITLE, 3, panel, false);
		
		loader.getCategory(onLoad);
		panel.addEventListener(CategoryClickEvent.CATEGORY_CLICK, onClick);
	}
	
	private function onClick(e : CategoryClickEvent) 
	{
		//trace(e.getName());
		this.getPanel().addTab(new CategoryTab(e.getId(), e.getName(), panel, viewerId));
	}
	
	private function onThisClick(catId : UInt, catName : String) : Dynamic -> Void
	{
		var categoryId = catId;
		var categoryName = catName;
		var p = this.getPanel();
		
		return function (dyn : Dynamic) : Void {
			p.dispatchEvent(new CategoryClickEvent(catId, catName));
		};
	}
	
	private function onLoad(data : Array<Category>) : Void 
	{
		var w : Float = 0;
		var h : Float = 0;
		var size : Float = 15 ;
		var count : Float = 0; 
		for (category in data)
		{
			count++;		
			var link = new HUGLinkButton(
							category.getName(),
							new TextFormat("Arial", size, 0x00ff00)
						);
			if (count == 5) { count = 0; size += -0.3; }
			w = (w + link.getBounds(content).width > 607) ? 0 : w + link.getBounds(content).width;
			h += (w == 0) ? 30 : 0;
			
			link.x = w - link.getBounds(content).width;
			link.y = h;
				
			link.addEventListener(MouseEvent.CLICK, onThisClick(category.getCatId(), category.getName()));
			
			content.addChild(link);
			
			//trace(category.getName());
		}
	}
		
}